package com.kakame.tibbers.common.directive;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
import com.kakame.tibbers.common.init.cache.ResourceCache;
import com.kakame.tibbers.common.models.AuthResource;

/**
 * 获取资源url指令
 * <pre>
 * 使用方式：
 * 
 * #resUrl('backend')
 * 
 * #end
 * </pre>
 * @author 何家明
 * @date 2018年11月24日 下午7:55:26
 */
public class ResourceUrlDirective extends Directive {
	
	/** 资源代码 */
	private Expr resourceCodeExpr;

	@Override
	public void setExprList(ExprList exprList) {
		int paramNum = exprList.length();  // 参数个数
		if(paramNum != 1) {
			throw new ParseException("resUrl指令中应当有且仅有一个参数", location);
		}
		this.resourceCodeExpr = exprList.getExpr(0);
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		Object resourceCodeObj = resourceCodeExpr.eval(scope);
		if(resourceCodeObj == null) {
			return;
		}
		String resourceCode = String.valueOf(resourceCodeObj);
		AuthResource authResource = ResourceCache.me.getByCode(resourceCode);
		write(writer, authResource.getResourceUrl());
	}
}
